<?php
/**
* A simple database connector
* @todo sqlite connector
* @todo postgresql connector
* @todo switch to mysqli for mysql
* @link http://webappkit.net
* @package webappkit
* @subpackage db
* @author J.Ducastel <jeremie@ducastel.name>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
class DbLinkTool extends WakTool {

    protected $cfg=array(
		'dblink'=>array(
			'host'=>'localhost'
			,'db'=>''
			,'user'=>'root'
			,'login'=>''
			,'encoding'=>''));

	protected $link;

    public static function toolFactory($kit_id,$cfg=array()) {
        return new DblinkTool($kit_id,$cfg);
    }

    /**
     * connects to database using configuration data
     * @access public
     * @return bool
     */
    public function connect() {
        // trying to connect user to host
        $host=$this->cfg['dblink']['host'];
        $user=$this->cfg['dblink']['user'];
        $pwd=$this->cfg['dblink']['pwd'];
        if (!$this->link=@mysql_connect($host,$user,$pwd)) {
            throw new Exception("could not connect user $user to host $host");
			return false;
		}
        // selecting db
        $db=$this->cfg['dblink']['db'];
        if (!$this->selectDb($db)) {
            throw new Exception("could not select db $db");
            // print_r($this);
            return false;
        }
        // setting encoding
        if ($encoding=$this->cfg['dblink']['encoding'] and !$this->setEncoding($encoding)) {
            throw new Exception("could not set encoding $encoding");
            // print_r($this);
            return false;
        }
		return true;
    }

    public function selectDb($db) {
		return @mysql_select_db($db, $this->link);
    }

	/**
	* executes a sql query, return resource
	* @access public
	* @param string $sql sql query
	* @param bool $buffered default to false
	* @return resource
	*/
	function & query($sql,$buffered=false) {
		// execute query
		if ($buffered) {
			$r=@mysql_query($sql,$this->link);
		} else {
			$r=@mysql_unbuffered_query($sql,$this->link);
		}
		return $r;
	}

    public function setEncoding($encoding) {
		// MySQL 4.1
		if (!$this->query("SET NAMES '$encoding'")
		// MySQL 4.0
		and !$this->query("SET CHARACTER SET '$encoding'")) {
			trigger_error("failed to set encoding $encoding : ".mysql_error());
			return false;
		}
		$this->encoding=$encoding;
		return true;
    }
}
